package cn.ztuo.bitrade.controller;

import cn.ztuo.bitrade.constant.BooleanEnum;
import cn.ztuo.bitrade.constant.MemberLevelEnum;
import cn.ztuo.bitrade.entity.Coin;
import cn.ztuo.bitrade.entity.LoanMoney;
import cn.ztuo.bitrade.entity.Member;
import cn.ztuo.bitrade.entity.MemberWallet;
import cn.ztuo.bitrade.entity.transform.AuthMember;
import cn.ztuo.bitrade.service.CoinService;
import cn.ztuo.bitrade.service.LoanMoneyService;
import cn.ztuo.bitrade.service.MemberService;
import cn.ztuo.bitrade.service.MemberWalletService;
import cn.ztuo.bitrade.util.BigDecimalUtils;
import cn.ztuo.bitrade.util.FileUtil;
import cn.ztuo.bitrade.util.Md5;
import cn.ztuo.bitrade.util.MessageResult;
import cn.ztuo.bitrade.vo.BorrowMoneyVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;

import static cn.ztuo.bitrade.constant.SysConstant.SESSION_MEMBER;

/**
 * @author: Xiazt
 * @date: 2020-04-27 14:25
 */
@RestController
@RequestMapping("loanMoney")
public class LoanMoneyController extends BaseController {

    @Autowired
    private LoanMoneyService loanMoneyService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private CoinService coinService;

    @Autowired
    private MemberWalletService memberWalletService;

    @RequestMapping("issueLoan")
    public MessageResult saveOrUpdate(@SessionAttribute(SESSION_MEMBER) AuthMember authMember, LoanMoney loanMoney, String jyPassword, HttpServletRequest request) {
        try {
            if (jyPassword == null || jyPassword.equals("")) return error("交易密码不能为空！");
            //验证用户信息
            Member member = memberService.findOne(authMember.getId());
            if (member.getTransactionStatus().equals(BooleanEnum.IS_FALSE)) return error("您当前账户已禁用，请联系客服！");
            if (member.getMemberLevel() == MemberLevelEnum.GENERAL) error("请先进行实名认证！");

            //验证交易密码
            String mbPassword = member.getJyPassword();
            if (mbPassword == null || mbPassword.equals("")) return MessageResult.error(500, "请先设置交易密码！");
            if (!Md5.md5Digest(jyPassword + member.getSalt()).toLowerCase().equals(mbPassword))
                return MessageResult.error(500, "交易密码错误！");
            if (loanMoney.getDayRate().compareTo(BigDecimal.ZERO) <= 0) {
                FileUtil.writeErrorLog(request.getRemoteAddr(), loanMoney.getDayRate(), authMember.getId());
                return error("数据异常！");
            }
            if (loanMoney.getPeriod() <= 0) {
                FileUtil.writeErrorLog(request.getRemoteAddr(), new BigDecimal(loanMoney.getPeriod()), authMember.getId());
                return error("数据异常！");
            }

            if (loanMoney.getLoanAmount().compareTo(BigDecimal.ZERO) <= 0) {
                FileUtil.writeErrorLog(request.getRemoteAddr(), loanMoney.getLoanAmount(), authMember.getId());
                return error("数据错误！");
            }

            // 计算利息
            BigDecimal dayRate = BigDecimalUtils.div(loanMoney.getDayRate(), new BigDecimal(100));
            BigDecimal interestDue = BigDecimalUtils.mul(BigDecimalUtils.mul(loanMoney.getLoanAmount(), dayRate), loanMoney.getPeriod());
            if (interestDue.compareTo(BigDecimal.ZERO) <= 0) return error("数据异常！");
            loanMoney.setMaturityYield(interestDue);

            // 验证余额
            Coin coin = coinService.findByUnit("USDT");
            MemberWallet memberWallet = memberWalletService.findByCoinAndMember(coin, member);
            if (memberWallet.getBalance().compareTo(loanMoney.getLoanAmount()) < 0) return error("余额不足！");
            loanMoneyService.saveOrUpdate(authMember.getId(), loanMoney, memberWallet);
            return success();
        } catch (Exception e) {
            e.printStackTrace();
            return error("服务器异常！");
        }

    }

    @RequestMapping("getLoanMoneyList")
    public MessageResult getBorrowMoneyList(BorrowMoneyVO borrowMoneyVO) {
        return success(loanMoneyService.getLoanMoneyList(borrowMoneyVO));
    }

    /**
     * 撤单
     *
     * @param authMember
     * @param id
     * @param jyPassword
     * @return
     */
    @RequestMapping("cancellations")
    public MessageResult cancellations(@SessionAttribute(SESSION_MEMBER) AuthMember authMember, Long id, String jyPassword) {
        try {
            if (jyPassword == null || jyPassword.equals("")) return error("交易密码不能为空！");
            // 验证用户信息
            Member member = memberService.findOne(authMember.getId());
            if (member.getTransactionStatus().equals(BooleanEnum.IS_FALSE)) return error("您当前账户已禁用，请联系客服！");
            if (member.getMemberLevel() == MemberLevelEnum.GENERAL) error("请先进行实名认证！");

            // 验证交易密码
            String mbPassword = member.getJyPassword();
            if (mbPassword == null || mbPassword.equals("")) return MessageResult.error(500, "请先设置交易密码！");
            if (!Md5.md5Digest(jyPassword + member.getSalt()).toLowerCase().equals(mbPassword))
                return MessageResult.error(500, "交易密码错误！");
            LoanMoney loanMoney = loanMoneyService.findById(id);
            if (loanMoney.getStatus() != 0) return error("该借贷已产生交易，不可撤单！");
            loanMoneyService.cancellations(authMember.getId(), loanMoney);
            return success();
        } catch (Exception e) {
            e.printStackTrace();
            return error("服务器异常！");
        }
    }

}
